package com.fruit.tool.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruit.normal.exception.FruitException;

public class ResultUtil {
	private static Logger log = LoggerFactory.getLogger(ResultUtil.class);
	
	public static ResultBean returnResult(Object result, String description) {
		ResultBean rb = new ResultBean();
		rb.setResult(result);
		rb.setDescription(description);
		rb.setStatus(ResultStatus.SUCCESS);
		return rb;
	};
	
	public static ResultBean returnResult(Exception e) {
		
		ResultBean rb = null;
		if(e instanceof FruitException) {
			FruitException te = (FruitException) e;
			rb = new ResultBean();
			rb.setDescription(te.getMessage());
			rb.setCode(te.getErrorCode());
			rb.setStatus(ResultStatus.FAIL);
		} else {
			e.printStackTrace();
			rb = new ResultBean();
			rb.setDescription("系统内部异常");
			rb.setStatus(ResultStatus.ERROR);
		}
		return rb;
	};
	
	public static String returnJson(Exception e) {
		ResultBean rb = returnResult(e);
		try {
			return (new ObjectMapper()).writeValueAsString(rb);
		} catch (JsonProcessingException e1) {
			log.error(e.getMessage(), e);
		}
		return "{\"status\":\"ERROR\",\"description\":\"系统内部异常\"}";
	};
}